package model

import (
	"encoding/json"
	"fmt"
	"gitee.com/wochong/HalloGin/package/util"
	"github.com/golang/glog"
	"github.com/jinzhu/gorm"
	"time"
)

type User struct {
	gorm.Model
	Name     string `json:"name" gorm:""`
	Phone    int    `json:"phone" gorm:""`
	Password string `json:"password" gorm:""`
	Email    string `json:"email" gorm:""`
	ParentID uint   `json:"parent_id" gorm:""`
	CheckSum string `json:"check_sum"`
}

func (u *User) AfterCreate(scope *gorm.Scope) (err error) {

	hash, err := u.CreateCheckSum()
	if err != nil {
		glog.Errorln(err)
		return err
	}

	fmt.Println("after CreateCheckSum:", *u)

	scope.DB().Model(u).Update("check_sum", hash)
	return
}

func (u *User) CreateCheckSum() (hash string, err error) {

	uData := *u

	uData.CreatedAt = time.Unix(0, 0)
	uData.UpdatedAt = time.Unix(0, 0)
	uData.DeletedAt = nil

	fmt.Println("uData:", uData)

	userByte, err := json.Marshal(uData)
	if err != nil {
		return "", err
	}

	return util.MD5Hash(userByte), nil
}

func (u *User) Add() (err error) {
	return db.Create(u).Error
}

func (u *User) Update() (err error) {
	return db.Model(&User{}).Update(u).Error
}

func (u *User) Updates(user *User) (err error) {
	return db.Model(u).Updates(user).Error
}

func AddUser(user *User) (err error) {
	return db.Create(user).Error
}

func DeleteUser(userID uint) (err error) {
	return db.Where("id", userID).Error
}

func GetUser(userID uint) (user *User, err error) {
	user = &User{}
	err = db.First(user, userID).Error
	return
}

func GetAllUser() (users []User, err error) {

	users = make([]User, 0)

	err = db.Find(&users).Error
	return
}

func UpdateUser(userID uint, user *User) (err error) {

	m := &User{}
	m.ID = userID

	return db.Model(m).Updates(user).Error
}
